﻿using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SNPAD 
{
    internal class Excel
    {

        /// <summary>
        /// 另存新档按钮
        /// </summary>
      public     static  void SaveAs(CCWin.SkinControl.SkinDataGridView dgvAgeWeekSex) //另存新档按钮   导出成Excel
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "Export Excel File To";
            saveFileDialog.ShowDialog();
            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string str = "";
            try
            {
                //写标题
                for (int i = 1; i < dgvAgeWeekSex.ColumnCount; i++)
                {
                    if (i > 1)
                    {
                        str += "\t";
                    }
                    str += dgvAgeWeekSex.Columns[i].HeaderText;
                }
                sw.WriteLine(str);
                //写内容
                for (int j = 0; j < dgvAgeWeekSex.Rows.Count; j++)
                {
                    string tempStr = "";
                    for (int k =1; k < dgvAgeWeekSex.Columns.Count; k++)
                    {
                        if (k > 1)
                        {
                            tempStr += "\t";
                        } 
                         tempStr += dgvAgeWeekSex.Rows[j].Cells[k].Value.ToString();
                        
                    }

                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
                MessageBox.Show("文件保存成功");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }
        public static void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)

        {



            if (tmpDataTable == null)

                return;

            int rowNum = tmpDataTable.Rows.Count;

            int columnNum = tmpDataTable.Columns.Count;

            int rowIndex = 1;

            int columnIndex = 0;

            Microsoft.Office.Interop.Excel.Application xlApp = new ApplicationClass();

            xlApp.DefaultFilePath = "";

            xlApp.DisplayAlerts = true;

            xlApp.SheetsInNewWorkbook = 1;

            Workbook xlBook = xlApp.Workbooks.Add(true);

            //将DataTable的列名导入Excel表第一行

            foreach (DataColumn dc in tmpDataTable.Columns)

            {

                columnIndex++;

                xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;

            }

            //将DataTable中的数据导入Excel中

            for (int i = 0; i < rowNum; i++)

            {

                rowIndex++;

                columnIndex = 0;

                for (int j = 0; j < columnNum; j++)

                {

                    columnIndex++;

                    xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();

                }

            }

            //xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));

            xlBook.SaveCopyAs(strFileName);

        }
        public static void ExportExcel(string fileName, CCWin.SkinControl.SkinDataGridView myDGV)
        {
            if (myDGV.Rows.Count > 0)
            {

                string saveFileName = "";
                //bool fileSaved = false;  
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.DefaultExt = "xlsx";
                saveDialog.Filter = "Excel文件|*.xlsx";
                saveDialog.FileName = fileName;
                saveDialog.ShowDialog();
                saveFileName = saveDialog.FileName;
                if (saveFileName.IndexOf(":") < 0) return; //被点了取消   
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
                if (xlApp == null)
                {
                    MessageBox.Show("无法创建Excel对象，可能您的机子未安装Excel");
                    return;
                }

                Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
                Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1  

                //写入标题  
                for (int i = 1; i < myDGV.ColumnCount; i++)
                {
                    worksheet.Cells[1, i ] = myDGV.Columns[i].HeaderText;
                }
                //写入数值  
                for (int r = 0; r < myDGV.Rows.Count; r++)
                {
                    for (int i = 1; i < myDGV.ColumnCount; i++)
                    {
                        worksheet.Cells[r + 2, i ] = myDGV.Rows[r].Cells[i].Value;
                    }
                    System.Windows.Forms.Application.DoEvents();
                }
                worksheet.Columns.EntireColumn.AutoFit();//列宽自适应  
                                                         //if (Microsoft.Office.Interop.cmbxType.Text != "Notification")  
                                                         //{  
                                                         //    Excel.Range rg = worksheet.get_Range(worksheet.Cells[2, 2], worksheet.Cells[ds.Tables[0].Rows.Count + 1, 2]);  
                                                         //    rg.NumberFormat = "00000000";  
                                                         //}  

                if (saveFileName != "")
                {
                    try
                    {
                        workbook.Saved = true;
                        workbook.SaveCopyAs(saveFileName);
                        //fileSaved = true;  
                    }
                    catch (Exception ex)
                    {
                        //fileSaved = false;  
                        MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
                    }

                }
                //else  
                //{  
                //    fileSaved = false;  
                //}  
                xlApp.Quit();
                GC.Collect();//强行销毁   
                             // if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL  
                MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK);
            }
            else
            {
                MessageBox.Show("报表为空,无表格需要导出", "提示", MessageBoxButtons.OK);
            }

        }
        public static void ExportToTxt(DataGridView dgv, string saveFileName)
        {
            bool fileSaved = false;
            SaveFileDialog saveDialog = new SaveFileDialog();
            //   "/*txt*/"
            saveDialog.DefaultExt = "";
            saveDialog.Filter = "Execl files(*.xls)|*.xls|Word文档(*.doc)|*.doc|txt(*.txt)|*.txt | CSV(*.csv)|*.csv";
            saveDialog.FileName = saveFileName;
            saveDialog.Title = "导出到";
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消

            Stream myStream;
            myStream = saveDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("GB2312"));

            try
            {
                int[] colContentLength = new int[dgv.ColumnCount];//控制列宽
                for (int col = 0; col < dgv.ColumnCount; col++)
                {
                    colContentLength[col] = dgv.Columns[col].HeaderText.Length;
                }

                for (int row = 0; row < dgv.RowCount; row++)
                {
                    for (int col = 0; col < dgv.ColumnCount; col++)
                    {
                        if (dgv.Rows[row].Cells[col].Value != null)
                        {
                            if (dgv.Rows[row].Cells[col].Value.ToString().Length > colContentLength[col])
                            {
                                colContentLength[col] = dgv.Rows[row].Cells[col].Value.ToString().Length;
                            }
                        }

                    }
                }

                int position = 0;
                foreach (DataGridViewColumn column in dgv.Columns)//写标题
                {
                    sw.Write(column.HeaderText.PadRight(colContentLength[position++]));
                    sw.Write("\t");
                }
                sw.WriteLine();

                for (int j = 0; j < dgv.RowCount; j++)//写内容
                {
                    string tempStr = "";
                    for (int k = 0; k < dgv.ColumnCount; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }

                        if (dgv.Rows[j].Cells[k].Value == null)
                        {
                            tempStr += "".PadRight(colContentLength[k]);
                        }
                        else
                        {
                            tempStr += dgv.Rows[j].Cells[k].Value.ToString().PadRight(colContentLength[k]);
                        }
                    }
                    sw.WriteLine(tempStr);
                }
                fileSaved = true;
            }

            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }


            finally
            {
                sw.Close();
                myStream.Close();
            }
            if (fileSaved == true)
                MessageBox.Show("导出数据完毕！", "tyj提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
    }
}



